package com.hutianao.gqgl.user.service.impl;

import com.hutianao.gqgl.login.entity.MenuLevelEntity;
import com.hutianao.gqgl.mybatis.entity.PtMenuEntity;
import com.hutianao.gqgl.mybatis.entity.PtUserEntity;
import com.hutianao.gqgl.mybatis.ztree.ZtreeEntity;
import com.hutianao.gqgl.spring.security.GdmtPasswordEncoder;
import com.hutianao.gqgl.user.entity.SearchUserEntity;
import com.hutianao.gqgl.user.repository.UserDao;
import com.hutianao.gqgl.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.jdbc.UncategorizedSQLException;
import org.springframework.stereotype.Service;
import com.hutianao.gqgl.mybatis.flexigrid.PaddingEntity;
import com.hutianao.gqgl.mybatis.flexigrid.PadingRstType;
import com.hutianao.gqgl.spring.util.DataUitl;
import org.springframework.util.DigestUtils;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

@Service("userService")
public class UserServiceImpl implements UserService {
    private final static  Integer MENU_FIRST = 1;
    @Resource
    private UserDao userDao;

    @Autowired
    private GdmtPasswordEncoder gdmtPasswordEncoder;

    @Value("${max_time_gap}")
    private Long max_time_gap;

    @Override
    public List<PtUserEntity> queryUserInfoListByName(SearchUserEntity search) {
        return userDao.queryUserInfoListByName(search);
    }

    @Override
    public void deleteUserInfoByIds(String ids) throws UncategorizedSQLException {
        String[] array = ids.split(",");
        for(String id: array){
            userDao.deleteUserInfoByIds(id);
        }

    }

    @Override
    public PtUserEntity queryUserInfoByName(String userName) {
        return userDao.queryUserInfoByName(userName);
    }

    @Override
    public List<PtMenuEntity> queryMenuList() {
        Locale locale = LocaleContextHolder.getLocale();

        return userDao.queryMenuListByLang(locale.toString());
    }

    @Override
    public List<MenuLevelEntity> queryMenuLevelList() {
        List<PtMenuEntity> ptMenuEntityList = queryMenuList();
        return dealMenuLevel(ptMenuEntityList);
    }

    @Override
    public void modifyUserInfoById(PtUserEntity ptUserEntity) {
        userDao.modifyUserInfoById(ptUserEntity);
    }

    @Override
    public List<String> queryrivilegeList(String userUuid) {
        return userDao.queryrivilegeList(userUuid);
    }

    @Override
    public PadingRstType<PtUserEntity> queryUserInfoListByPage(SearchUserEntity entity, PaddingEntity paddingEntity) {
        paddingEntity.deal(PtUserEntity.class);

        PadingRstType<PtUserEntity> padingRstType = new PadingRstType<>();
        padingRstType.setPage(paddingEntity.getPage());
        List<PtUserEntity> list = userDao.queryUserInfoListByPage(entity,paddingEntity);
        padingRstType.setRawRecords(list);
        Integer total = userDao.queryUserInfoTotal(entity);
        padingRstType.setTotal(total);
        padingRstType.putItems();
        return padingRstType;
    }

    @Resource
    private MessageSource messageSource;
    @Override
    public List<ZtreeEntity> queryRoleTreeList(String userUuid) {

        List<ZtreeEntity> list = userDao.queryRoleTreeList();
        ZtreeEntity ztreeEntity =new ZtreeEntity();
        ztreeEntity.setId("-1");
        Locale locale = LocaleContextHolder.getLocale();
        String roleInfo = messageSource.getMessage("role.info",null,locale);
        ztreeEntity.setName(roleInfo);
        ztreeEntity.setpId("-2");
        list.add(ztreeEntity);

        List<String> roleUuuidList =  userDao.queryRoleByUserUuuid(userUuid);
        for(ZtreeEntity ztreeEntityItem:list){
            if(roleUuuidList.contains(ztreeEntityItem.getId())){
                ztreeEntityItem.setChecked(true);
            }
        }

        return list;
    }

    @Override
    public void saveUserIdAndRoleId(String userUuid, String roleArray) {
        userDao.delRoleByUserId(userUuid);
        String[] roleIds = roleArray.split(",");
        for(String roleId: roleIds){
            userDao.insertRoleRefUser(userUuid,roleId);
        }

    }

    @Override
    public List<MenuLevelEntity> queryMenuLevelList(String userUuid) {
        Locale lang = LocaleContextHolder.getLocale();

        List<PtMenuEntity> ptMenuEntityList = userDao.queryMenuLevelListByUserUuid(userUuid,lang.toString());

        return  dealMenuLevel(ptMenuEntityList);

    }

    private List<MenuLevelEntity> dealMenuLevel(List<PtMenuEntity> ptMenuEntityList) {
        List<MenuLevelEntity> menuLevelEntityList = new ArrayList<>();
        MenuLevelEntity menuLevelEntity1;
        MenuLevelEntity menuLevelEntity2;
        MenuLevelEntity menuLevelEntity3;
        for (PtMenuEntity menu1 : ptMenuEntityList) {
            // 一级菜单
            if (MENU_FIRST.equals(menu1.getMenuLevel())) {
                menuLevelEntity1 = new MenuLevelEntity(menu1);
                menuLevelEntityList.add(menuLevelEntity1);
                for (PtMenuEntity menu2 : ptMenuEntityList) {
                    //二级菜单
                    if (menuLevelEntity1.getMenuId().equals(menu2.getParentId())) {
                        menuLevelEntity2 = new MenuLevelEntity(menu2);
                        menuLevelEntity1.addChildren(menuLevelEntity2);
                        //三级菜单
                        for (PtMenuEntity menu3 : ptMenuEntityList) {
                            if (menuLevelEntity2.getMenuId().equals(menu3.getParentId())) {
                                menuLevelEntity3 = new MenuLevelEntity(menu3);
                                menuLevelEntity2.addChildren(menuLevelEntity3);

                            }
                        }
                    }
                }
            }
        }
        return menuLevelEntityList;
    }
    @Override
    public String addUserInfo(PtUserEntity ptUserEntity) {
        PtUserEntity ptUserEntity_1 = userDao.queryUserInfoByName(ptUserEntity.getUserName());
        if(ptUserEntity_1 ==null){
            try{
                ptUserEntity.setUserUuid(DataUitl.getUuid());
                String password = gdmtPasswordEncoder.encode(ptUserEntity.getPassword());
//                String passwd = "1qaz";
//                String password= DigestUtils.md5DigestAsHex((passwd + "abc123456abc").getBytes());
                ptUserEntity.setPassword(password);
                ptUserEntity.setRegisterdate(new Date());
                userDao.insertUserInfo(ptUserEntity);
                return "user.add.success";
            }catch (Exception e){
                e.printStackTrace();
                return "error"+e.getMessage();
            }
        }
        return "user.add.error.repeat";
    }

    @Override
    public void modifyUserInfo(PtUserEntity ptUserEntity) {
        userDao.modifyUserInfo(ptUserEntity);
    }

    @Override
    public void deleteUserById(String userUuidArray) {
        String[] userUuids = userUuidArray.split(",");
        userDao.deleteUserById(userUuids);

    }

    @Override
    public List<ZtreeEntity> queryDepTree(String userUuid) {
        List<ZtreeEntity> list = userDao.queryDepTree();
        List<String> depIds = userDao.queryDepByUserId(userUuid);
        for(ZtreeEntity ztreeEntity: list){
            if(depIds.contains(ztreeEntity.getId())){
                ztreeEntity.setChecked(true);
            }
        }
        return list;
    }

    @Override
    public void saveUserDep(String userUuid, String depIds) {
//        userDao.deleteDepByUserId(userUuid);
        userDao.insertUserRefDep(userUuid, depIds);


    }
    @Override
    public PtUserEntity queryUserInfoByMail(String email) {
        List<PtUserEntity> list = userDao.queryUserInfoByMail(email);
        if(list == null || list.size() == 0){
            return null;
        }
        return list.get(0);
    }


    @Override
    public void unlockUserById(String ids) {
        String[] array = ids.split(",");
        for(String id: array){
            userDao.unlockUserById(id,new Date());
        }
    }

    @Override
    public PtUserEntity queryIsSumUserInfoByName(String username) {
        Long time= System.currentTimeMillis()-max_time_gap;
        Date date = new Date(time);
        return userDao.queryIsSumUserInfoByName(username,date);
    }
    @Override
    public String checkPwd(String username, String password, String newpassword) {
        PtUserEntity ptUserEntity = userDao.queryUserInfoByName(username);
        if(gdmtPasswordEncoder.encode(password).equals(ptUserEntity.getPassword())){
            String encode = gdmtPasswordEncoder.encode(newpassword);
            userDao.updatePasswordByUserName(username,encode);
            return "user.updatePwd.success";
        }else{
            return "user.checkPwd.error";
        }
    }
}